<!-- 订单添加/编辑组件 -->
<template>
  <div>
    <el-form :inline="true" ref="form" :model="form" :rules="rules" label-width="180px">

      <el-divider content-position="left"><span class="divider_color">网络货运经营者信息 (企业信息)</span></el-divider>
      <el-row>
        <el-col :span="8">
          <el-form-item label="网络货运经营者名称" prop="carrier">
            <el-input class="o_input" v-model="form.carrier" placeholder="请输入内容" :readonly="readOnly2" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditIdentifier">
            <el-input class="o_input" v-model="form.unifiedSocialCreditIdentifier" placeholder="请输入统一社会信用代码" :readonly="readOnly2" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="道路运输经营许可证编号" prop="permitNumber">
            <el-input v-model="form.permitNumber" placeholder="请输入道路运输经营许可证编号" :readonly="readOnly2" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left"><span class="divider_color">订单信息</span></el-divider>
      <el-row>
        <el-col :span="8">
          <el-form-item label="上游企业委托运输单号" prop="originalDocumentNumber">
            <el-input class="o_input" v-model="form.originalDocumentNumber" placeholder="请输入上游企业委托运输单号" :readonly="readOnly1" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运单号" prop="shippingNoteNumber">
            <el-input class="o_input" v-model="form.shippingNoteNumber" placeholder="请输入运单号" :readonly="readOnly2" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分段分单号" prop="serialNumber">
            <span slot="label">
              分段分单号
              <el-tooltip effect="dark" placement="top">
                <div slot="content">
                  分段运输和多车运输由四位数字组成，前两位代表一单多车的序号，后两位代表分段序号。
                  <br/>
                  若运输形式为一单一车填0000
                </div>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-input v-model="form.serialNumber" maxlength="4" placeholder="请输入分段分单号" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="业务类型" prop="businessTypeCode">
            <el-select class="o_select" v-model="form.businessTypeCode" placeholder="请选择业务类型" :disabled="readOnly2">
              <el-option
                v-for="item in businessTypeOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运输组织类型" prop="transportTypeCode">
            <el-select class="o_select" v-model="form.transportTypeCode" placeholder="请选择运输组织类型" :disabled="readOnly2">
              <el-option
                v-for="item in transportTypeOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运输总车辆数" prop="vehicleAmount">
            <el-input-number v-model="form.vehicleAmount" :min="1" step-strictly disabled></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="发货时间" prop="leaveTime">
            <el-date-picker class="o_picker" :clearable="false" :disabled="readOnly1"
              v-model="form.leaveTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择发货时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收货时间" prop="arriveTime">
            <el-date-picker class="o_picker" :clearable="false" :disabled="readOnly1"
              v-model="form.arriveTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择收货时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运费金额(元)" prop="totalMonetaryAmount">
            <el-input-number v-model="form.totalMonetaryAmount" :precision="3" :min="1" :step="0.1" :disabled="readOnly2"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="货物名称" prop="descriptionOfGoods">
            <el-input class="o_input" v-model="form.descriptionOfGoods" placeholder="请输入货物名称" :readonly="readOnly1" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="货物类型" prop="cargoTypeClassificationCode">
            <el-select class="o_select" v-model="form.cargoTypeClassificationCode" placeholder="请选择货物类型" :disabled="readOnly1">
              <el-option
                v-for="item in cargoTypeClassificationOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="货物毛重(千克)" prop="goodsItemGrossWeight">
            <el-input-number v-model="form.goodsItemGrossWeight" :precision="3" :min="0.1" :step="0.1" :disabled="readOnly1"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" maxlength="200" placeholder="请输入备注" style="width: 381%;" :readonly="readOnly1" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left"><span class="divider_color">发货信息</span></el-divider>
      <el-row>
        <el-col :span="10">
          <el-form-item label="托运人名称" prop="consignor">
            <span slot="label">
              货源方
              <el-tooltip effect="dark" placement="top">
                <div slot="content">
                  未认证或被禁用的货源方不在可选列表
                </div>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-select class="o_select" v-model="form.consignor" filterable placeholder="请选择货源方" :disabled="readOnly1"
              @change="changeCompany">
              <el-option
                v-for="item in companyOptions"
                :key="item.id"
                :label="item.shortName"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="统一社会信用代码或个人证件号码" prop="consignorId" label-width="200">
            <el-input v-model="form.consignorId" placeholder="请输入托运人统一社会信用代码或个人证件号码" style="width: 245%;" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="国家行政区划" prop="fValue">
            <el-cascader class="o_select" placeholder="请选择装货地点的省市区" :disabled="readOnly1"
              v-model="form.fValue"
              :options="options"
              @change="handleChangeF">
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="装货地址" prop="placeOfLoading" label-width="200">
            <el-input v-model="form.placeOfLoading" placeholder="请输入装货地址" @blur="blurF" style="width: 320%;" :readonly="readOnly1" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="装货联系人" prop="loadLinker">
            <el-input class="o_input" v-model="form.loadLinker" placeholder="请输入装货联系人" :readonly="readOnly1" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="装货联系电话" prop="loadLinkTel">
            <el-input class="o_input" v-model="form.loadLinkTel" placeholder="请输入装货联系电话" :readonly="readOnly1" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left"><span class="divider_color">收货信息</span></el-divider>
      <el-row>
        <el-col :span="10">
          <el-form-item label="收货方名称" prop="consignee">
            <el-input class="o_input" v-model="form.consignee" placeholder="请输入收货方名称" :readonly="readOnly1" />
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="统一社会信用代码或个人证件号码" prop="consigneeId" label-width="200">
            <el-input v-model="form.consigneeId" placeholder="请输入收货方统一社会信用代码或个人证件号码" style="width: 250%;" :readonly="readOnly1" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="国家行政区划" prop="sValue">
            <el-cascader class="o_select" placeholder="请选择收货地点的省市区" :disabled="readOnly1"
              v-model="form.sValue"
              :options="options"
              @change="handleChangeS">
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="收货地址" prop="goodsReceiptPlace" label-width="200">
            <el-input v-model="form.goodsReceiptPlace" placeholder="请输入收货地址" @blur="blurS" style="width: 320%;" :readonly="readOnly1" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="收货联系人" prop="receiptLinker">
            <el-input class="o_input" v-model="form.receiptLinker" placeholder="请输入收货联系人" :readonly="readOnly1" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收货联系电话" prop="receiptLinkTel">
            <el-input class="o_input" v-model="form.receiptLinkTel" placeholder="请输入收货联系电话" :readonly="readOnly1" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-divider content-position="left"><span class="divider_color">承运信息</span></el-divider>
      <el-row>
        <el-col :span="8">
          <el-form-item label="实际承运人名称" prop="actualCarrierName">
            <span slot="label">
              司机姓名
              <el-tooltip effect="dark" placement="top">
                <div slot="content">
                  取得道路运输经营许可证的个体运输业户，直接填写“许可证上的业户名称”。
                  <br/>
                  其他情况填写“运输公司名称（合同签订人姓名）”。
                  <br/>
                  未认证或被禁用的司机不在可选列表
                </div>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-select class="o_select" v-model="form.actualCarrierName" filterable placeholder="请选择司机" :disabled="readOnly2"
              @change="changeDriver">
              <el-option
                v-for="item in driverOptions"
                :key="item.id"
                :label="item.driverName"
                :value="item">
                  <span style="float: left">{{ item.driverName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.telephone }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <!-- <el-form-item label="统一社会信用代码或个人证件号码" prop="actualCarrierId" label-width="200">
            <el-input v-model="form.actualCarrierId" placeholder="请输入实际承运人统一社会信用代码或个人证件号码" style="width: 245%;" />
          </el-form-item> -->
          <el-form-item label="司机电话" prop="driverPhone">
            <el-input class="o_input" v-model="form.driverPhone" placeholder="请选择司机" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="车辆牌照号" prop="vehicleNumber">
            <span slot="label">
              车辆牌照号
              <el-tooltip effect="dark" placement="top">
                <div slot="content">
                  请选择牵引车等有动力的车辆。
                  <br/>
                  未认证或被禁用的车辆不在可选列表
                </div>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-select class="o_select" v-model="form.vehicleNumber" filterable placeholder="请选择车辆" :disabled="readOnly2"
              @change="changeVehicle">
              <el-option
                v-for="item in vehicleOptions"
                :key="item.id"
                :label="item.vehicleNumber"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="道路运输经营许可证号" prop="actualCarrierBusinessLicense">
            <el-input class="o_input" v-model="form.actualCarrierBusinessLicense" placeholder="请搜索车辆" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="挂车牌照号" prop="trailerVehiclePlateNumber">
            <span slot="label">
              挂车牌照号
              <el-tooltip effect="dark" placement="top">
                <div slot="content">
                  左侧车辆为牵引车的必填。
                  <br/>
                  请选择全挂车等无动力的车辆。
                  <br/>
                  未认证或被禁用的车辆不在可选列表
                </div>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-select class="o_select" v-model="form.trailerVehiclePlateNumber" filterable clearable placeholder="输入挂车车牌搜索车辆" :disabled="readOnly2"
              @change="changeVehicleG" @clear="clearVehicleG">
              <el-option
                v-for="item in vehicleOptions"
                :key="item.id"
                :label="item.vehicleNumber"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <div>
        <el-button v-if="is_bx" type="warning" @click="ycBx" :disabled="readOnly1">隐藏保险信息</el-button>
        <el-button v-else type="warning" @click="tjBx" :disabled="readOnly1">添加保险信息</el-button>
      </div>
      <div v-if="is_bx">
        <el-divider content-position="left"><span class="divider_color">保险信息</span></el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="保险单号" prop="policyNumber">
              <el-input class="o_input" v-model="form.policyNumber" placeholder="请输入保险单号" :readonly="readOnly1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保险公司" prop="insuranceCompanyCode">
              <el-select class="o_select" v-model="form.insuranceCompanyCode" filterable placeholder="请选择保险公司" :disabled="readOnly1">
                <el-option
                  v-for="item in insuranceCompanyOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <el-divider content-position="left"><span class="divider_color">费用信息</span></el-divider>
      <!-- 统计 -->
      <div style="margin-bottom: 1%">
        <el-tag type="success" size="default" > 应收：{{sumFlowIn}} 元 </el-tag>&nbsp;
        <el-tag type="danger" size="default" > 应付：{{sumFlowOut}} 元 </el-tag>&nbsp;
        <el-tag type="blue" size="default" > 利润：{{flowTotal}} 元 </el-tag>
      </div>
      <div>
        <el-row :gutter="5">
          <el-col :span="12">

            <!-- 添加按钮 -->
            <el-button class="specBtn" type="primary" @click="addLine(1)" circle :disabled="readOnly2"><i class="el-icon-plus"></i></el-button>

            <el-table :data="flowListIn" border>
              <el-table-column type="index" width="50"></el-table-column>
              <el-table-column label="应收费用" align="center">
                <template slot-scope="scope">
                  <el-select size="small" v-model="scope.row.flowType" filterable clearable
                    placeholder="请选择费用类型" :disabled="readOnly2">
                    <el-option
                      v-for="dict in opFlowTypeIn"
                      :key="dict.id"
                      :label="dict.name"
                      :value="dict.id"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="金额" align="center">
                <template slot-scope="scope">
                  <el-input-number :precision="2" :step="0.1" :min="0.00" size="small"
                    v-model="scope.row.amount" placeholder="请输入金额" style="width: 100%"
                    @change="sumFlow"
                    :disabled="readOnly2">
                  </el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="客户" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.companyId" filterable placeholder="请选择客户" clearable :disabled="readOnly2">
                    <el-option
                      v-for="item in opCompany"
                      :key="item.id"
                      :label="item.shortName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="司机" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.driverId" filterable placeholder="请选择司机" clearable :disabled="readOnly2">
                    <el-option
                      v-for="item in opDriver"
                      :key="item.id"
                      :label="item.driverName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="删除" align="center" width="80">
                <template slot-scope="scope">
                  <el-button type="danger" @click="delLine(scope.$index, scope.row, 1)" icon="el-icon-delete" circle :disabled="readOnly2"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>

          <el-col :span="12">
            <!-- 添加按钮 -->
            <el-button class="specBtn2" type="primary" @click="addLine(2)" circle :disabled="readOnly2"><i class="el-icon-plus"></i></el-button>

            <el-table :data="flowListOut" border >
              <el-table-column type="index" width="50"></el-table-column>
              <el-table-column label="应付费用" align="center">
                <template slot-scope="scope">
                  <el-select size="small" v-model="scope.row.flowType" filterable
                    placeholder="请选择费用类型" clearable :disabled="readOnly2">
                    <el-option
                      v-for="item in opFlowTypeOut"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="金额" align="center">
                <template slot-scope="scope">
                  <el-input-number  :precision="2" :step="0.1" :min="0.00" size="small"
                    v-model="scope.row.amount" style="width: 100%" placeholder="请输入金额"
                    @change="sumFlow"
                    :disabled="readOnly2"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="司机" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.driverId" placeholder="请选择司机" filterable clearable :disabled="readOnly2">
                    <el-option
                      v-for="item in opDriver"
                      :key="item.id"
                      :label="item.driverName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="客户" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.companyId" filterable placeholder="请选择客户" clearable :disabled="readOnly2">
                    <el-option
                      v-for="item in opCompany"
                      :key="item.id"
                      :label="item.shortName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="删除" align="center" width="80">
                <template slot-scope="scope">
                  <el-button type="danger" @click="delLine(scope.$index, scope.row, 2)" icon="el-icon-delete" circle :disabled="readOnly2"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>

      <div v-if="readOnly2">
        <el-divider content-position="left"><span class="divider_color">回单信息</span></el-divider>
        <el-form-item v-for="(file, index) in fileList" :key="index" label="">
          <el-image :src="file" fit="fit" style="width: 160px; height: 160px"/>
        </el-form-item>
      </div>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="!readOnly2" type="primary" :disabled="disabled" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { listOrder, getOrder, getOrderInfo, delOrder, addOrder, updateOrder } from "@/api/tws/order";
import { listQy } from "@/api/tws/qy";
import { listCompany, listCompanyAll } from "@/api/tws/company";
import { listVehicle, listVehicleAll } from "@/api/tws/vehicle";
import { listDriver, listDriverAll } from "@/api/tws/driver";
import { provinceAndCityData, regionData, provinceAndCityDataPlus, regionDataPlus, CodeToText, TextToCode } from 'element-china-area-data';
// import { getFlowType } from "@/api/tws/paymentFlowType";
// import { delFlow } from "@/api/tws/paymentFlow";

export default {
  name: 'OrderForm',
  components: {
  },
  props: {
    // 1新增 2修改 3查看
    mode: {
      type: String
    },
    orderId: {
      type: String
    }
  },
  data() {
    return {
      // 禁用确定按钮
      disabled: false,
      // 是否显示保险信息
      is_bx: true,
      // 可修改
      readOnly1: false,
      readOnly2: false,
      // 网络货运经营者信息
      agent: null,
      // 货源方列表
      companyOptions: [],
      // 司机列表
      driverOptions: [],
      // 车辆列表
      vehicleOptions: [],
      //应收
      sumFlowIn: 0.00,
      //应付
      sumFlowOut: 0.00,
      //利润
      flowTotal: 0.00,
      //应收流水类型
      opFlowTypeIn: [],
      //应付流水类型
      opFlowTypeOut: [],
      // 流水应收表格数据
      flowListIn: [],
      // 流水应付表格数据
      flowListOut: [],
      // 费用信息中的货源方列表(装货信息中选择的货源方)
      opCompany: [],
      // 费用信息中的司机列表(承运信息中选择的司机)
      opDriver: [],
      // 省市区
      options: regionData,
      // 业务类型字典数据
      businessTypeOptions: [],
      // 运输组织类型字典数据
      transportTypeOptions: [],
      // 货物类型字典数据
      cargoTypeClassificationOptions: [],
      // 保险公司字典数据
      insuranceCompanyOptions: [],
      // 订单状态字典数据
      statusOptions: [],
      // 回单照片
      fileList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        originalDocumentNumber: [
          { required: true, message: "上游企业委托运输单号不能为空", trigger: "blur" }
        ],
        shippingNoteNumber: [
          { required: true, message: "运单号不能为空", trigger: "blur" }
        ],
        serialNumber: [
          { required: true, message: "分段分单号不能为空", trigger: "blur" }
        ],
        vehicleAmount: [
          { required: true, message: "运输总车辆数不能为空", trigger: "blur" }
        ],
        transportTypeCode: [
          { required: true, message: "运输组织类型不能为空", trigger: ["blur", "change"] }
        ],
        carrier: [
          { required: true, message: "网络货运经营者名称不能为空", trigger: "blur" }
        ],
        unifiedSocialCreditIdentifier: [
          { required: true, message: "统一社会信用代码不能为空", trigger: "blur" }
        ],
        permitNumber: [
          { required: true, message: "道路运输经营许可证编号不能为空", trigger: "blur" }
        ],
        businessTypeCode: [
          { required: true, message: "业务类型不能为空", trigger: ["blur", "change"] }
        ],
        leaveTime: [
          { required: true, message: "发货时间不能为空", trigger: "blur" }
        ],
        arriveTime: [
          { required: true, message: "收货时间不能为空", trigger: "blur" }
        ],
        totalMonetaryAmount: [
          { required: true, message: "运费金额不能为空", trigger: "blur" }
        ],
        descriptionOfGoods: [
          { required: true, message: "货物名称不能为空", trigger: "blur" }
        ],
        cargoTypeClassificationCode: [
          { required: true, message: "货物类型不能为空", trigger: ["blur", "change"] }
        ],
        goodsItemGrossWeight: [
          { required: true, message: "货物毛重不能为空", trigger: "blur" }
        ],
        consignor: [
          { required: true, message: "托运人名称不能为空", trigger: ["blur", "change"] }
        ],
        consignorId: [
          { required: true, message: "托运人统一社会信用代码或个人证件号不能为空", trigger: ["blur", "change"] }
        ],
        placeOfLoading: [
          { required: true, message: "装货地址不能为空", trigger: "blur" }
        ],
        fValue: [
          { required: true, message: "装货地点的国家行政区划代码或国别代码不能为空", trigger: ["blur", "change"] }
        ],
        consignee: [
          { required: true, message: "收货方名称不能为空", trigger: "blur" }
        ],
        goodsReceiptPlace: [
          { required: true, message: "收货地址不能为空", trigger: "blur" }
        ],
        sValue: [
          { required: true, message: "收货地点的国家行政区划代码或国别代码不能为空", trigger: ["blur", "change"] }
        ],
        actualCarrierName: [
          { required: true, message: "实际承运人名称不能为空", trigger: ["blur", "change"] }
        ],
        actualCarrierBusinessLicense: [
          { required: true, message: "实际承运人道路运输经营许可证号不能为空", trigger: ["blur", "change"] }
        ],
        actualCarrierId: [
          { required: true, message: "实际承运人统一社会信用代码或证件号码不能为空", trigger: ["blur", "change"] }
        ],
        vehicleNumber: [
          { required: true, message: "车辆牌照号不能为空", trigger: ["blur", "change"] }
        ],
        policyNumber: [
          { required: true, message: "保险单号不能为空", trigger: "blur" }
        ],
        insuranceCompanyCode: [
          { required: true, message: "保险公司不能为空", trigger: ["blur", "change"] }
        ],
      }
    };
  },
  watch: {
    mode: function(newD, oldD) {
      if(newD) {
        // this.$nextTick(() => {})
        this.reset();
        // 新增
        if(newD == '1') {
          // 生成订单号
          getOrderNo().then(res => {
            this.form.originalDocumentNumber = res.data.originalDocumentNumber;
            this.form.shippingNoteNumber = res.data.shippingNoteNumber;
          })
          // 网络货运经营者信息
          if(this.agent) {
            this.form.carrier = this.agent.entName;
            this.form.unifiedSocialCreditIdentifier = this.agent.unifiedSocialCreditIdentifier;
            this.form.permitNumber = this.agent.permitNumber || this.agent.areaCode + '000000';
          }
          // 应收
          for(let i = 0; i < this.opFlowTypeIn.length; i++){
            this.flowListIn.push({
              flowType: this.opFlowTypeIn[i].id,
              amount: null,
              companyId: null,
              driverId: null
            });
          }
          // 应付
          for(let i = 0; i < this.opFlowTypeOut.length; i++){
            this.flowListOut.push({
              flowType : this.opFlowTypeOut[i].id,
              amount: null,
              companyId: null,
              driverId: null
            });
          }
        } else if(newD == '2') {
          // 修改
          this.getOrderInfo(this.orderId);
        } else if(newD == '3') {
          this.getOrderInfo(this.orderId);
          // 查看模式只读, 不可修改
          this.readOnly1 = true;
          this.readOnly2 = true;
        }
      }
    },
    deep: true // 可以深度检测到 obj 对象的属性值的变化
  },
  created() {
    // 业务类型字典
    this.getDicts("business_type").then(response => {
      this.businessTypeOptions = response.data;
    });
    // 运输组织类型字典
    this.getDicts("transport_type").then(response => {
      this.transportTypeOptions = response.data;
    });
    // 货物类型字典
    this.getDicts("cargo_type_classification").then(response => {
      this.cargoTypeClassificationOptions = response.data;
    });
    // 保险公司字典
    this.getDicts("insurance_company").then(response => {
      this.insuranceCompanyOptions = response.data;
    });
    // 获取流水账目
    this.getFlowType();
    // 获取企业(网络货运经营者)信息
    this.getQY();
    // 初始化地图插件
    this.initMap();
    // 获取所有货源方
    this.getCompanys();
    // 获取所有司机
    this.getDrivers();
    // 获取所有车辆
    // this.getVehicles();
  },
  methods: {
    // 初始化高德地图插件
    initMap() {
      AMap.plugin('AMap.Geocoder', () => {
        let GeocoderOptions = {
          city: '全国'
        };
        this.geocoder = new AMap.Geocoder(GeocoderOptions);
      });
    },
    // 获取企业(网络货运经营者)信息
    getQY() {
      listQy().then(response => {
        this.agent = response.data;
        // 如果没有网络货运经营者信息
        if(!this.form.carrier || !this.form.unifiedSocialCreditIdentifier || !this.form.permitNumber) {
          this.form.carrier = this.agent.entName;
          this.form.unifiedSocialCreditIdentifier = this.agent.unifiedSocialCreditIdentifier;
          this.form.permitNumber = this.agent.permitNumber || this.agent.areaCode + '000000';
        }
      });
    },
    // 获取所有货源方
    getCompanys() {
      let queryParam = {
        isCert: '2',
        state: '1'
      }
      listCompanyAll(queryParam).then(response => {
        this.companyOptions = response.data;
      });
    },
    // 获取所有司机
    getDrivers() {
      let queryParam = {
        isCert: '2',
        state: '1'
      }
      listDriverAll(queryParam).then(response => {
        this.driverOptions = response.data;
      });
    },
    // 获取所有车辆
    getVehicles() {
      let queryParam = {
        isCert: '2',
        state: '1'
      }
      listVehicleAll(queryParam).then(response => {
        this.vehicleOptions = response.data;
      });
    },
    // 查询流水账目
    getFlowType() {
      let queryFlowTypeParams = {
        isUsed: 1, //是否常用 1常用0不常用
        status: 1, //1 可用 2禁用
        type: null, //1应收 2应付
      }
      // 查询应收
      queryFlowTypeParams.type = 1;
      getFlowType(queryFlowTypeParams).then(response => {
        this.opFlowTypeIn = response.data;
        //应收
        this.flowListIn = [];
        for(let i = 0; i < this.opFlowTypeIn.length; i++){
          this.flowListIn.push({
            flowType: this.opFlowTypeIn[i].id,
            amount: null,
            companyId: null,
            driverId: null
          });
        }
      });
      // 查询应付
      queryFlowTypeParams.type = 2;
      getFlowType(queryFlowTypeParams).then(response => {
        this.opFlowTypeOut = response.data;
        //应付
        this.flowListOut = [];
        for(let i = 0; i < this.opFlowTypeOut.length; i++){
          this.flowListOut.push({
            flowType : this.opFlowTypeOut[i].id,
            amount: null,
            companyId: null,
            driverId: null
          });
        }
      });
    },
    // 获取订单
    getOrderInfo(orderId) {
      this.$nextTick(() => {
        getOrderInfo(orderId).then(response => {
          this.form = response.data.order;
          if(this.form.transportTypeCode) {
            this.form.transportTypeCode = this.form.transportTypeCode + '';
          }
          this.form.fValue = this.form.countrySubdivisionValue.split("-");
          this.form.sValue = this.form.countrySubdivisionValueS.split("-");
          this.flowListIn = response.data.flowListIn || [];
          this.flowListOut = response.data.flowListOut || [];
          // 如果没有订单号，生成订单号
          if(!this.form.shippingNoteNumber) {
            getOrderNo().then(res => {
              this.form.shippingNoteNumber = res.data.shippingNoteNumber;
            })
          }
          // 分段分单号
          if(!this.form.serialNumber) {
            this.form.serialNumber = '0000';
          }
          // 如果没有网络货运经营者信息
          if(!this.form.carrier || !this.form.unifiedSocialCreditIdentifier || !this.form.permitNumber) {
            this.form.carrier = this.agent.entName;
            this.form.unifiedSocialCreditIdentifier = this.agent.unifiedSocialCreditIdentifier;
            this.form.permitNumber = this.agent.permitNumber || this.agent.areaCode + '000000';
          }
          // 如果是货源转订单，禁用货源方填写的部分
          if(this.form.source == '1') {
            this.readOnly1 = true;
          }
          // 保险信息
          if(this.form.policyNumber == 'none') {
            this.is_bx = false;
          } else {
            this.is_bx = true;
          }
          if(this.flowListIn.length == 0) {
            // 应收
            for(let i = 0; i < this.opFlowTypeIn.length; i++){
              this.flowListIn.push({
                flowType: this.opFlowTypeIn[i].id,
                amount: null,
                companyId: this.form.companyId || null,
                driverId: null
              });
            }
          }
          if(this.flowListOut.length == 0) {
            // 应付
            for(let i = 0; i < this.opFlowTypeOut.length; i++){
              this.flowListOut.push({
                flowType : this.opFlowTypeOut[i].id,
                amount: null,
                companyId: null,
                driverId: this.form.driverId || null
              });
            }
          }
          // 费用信息 -> 货源方
          this.companyOptions.forEach(company => {
            if(company.id == this.form.companyId) {
              this.opCompany.push(company);
            }
          })
          // 费用信息 -> 司机
          this.driverOptions.forEach(driver => {
            if(driver.id == this.form.driverId) {
              this.opDriver.push(driver);
            }
          })
          // 回单照片
          if(this.form.backImages) {
            this.fileList = this.form.backImages.split(",");
          }
          //重新计算统计
          this.sumFlow();
        });
      })
      
    },
    // 取消按钮
    cancel() {
      this.huidiao();
    },
    huidiao() {
      this.reset();
      this.$emit("close");
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        originalDocumentNumber: null,
        shippingNoteNumber: null,
        serialNumber: '0000',
        vehicleAmount: null,
        transportTypeCode: null,
        carrier: null,
        unifiedSocialCreditIdentifier: null,
        permitNumber: null,
        businessTypeCode: null,
        despatchActualDateTime: null,
        goodsReceiptDateTime: null,
        totalMonetaryAmount: null,
        descriptionOfGoods: null,
        cargoTypeClassificationCode: null,
        goodsItemGrossWeight: null,
        consignor: null,
        consignorId: null,
        placeOfLoading: null,
        countrySubdivisionCode: null,
        countrySubdivisionValue: null,
        countrySubdivisionLabel: null,
        loadLinker: null,
        loadLinkTel: null,
        consignee: null,
        consigneeId: null,
        goodsReceiptPlace: null,
        countrySubdivisionCodeS: null,
        countrySubdivisionValueS: null,
        countrySubdivisionLabelS: null,
        receiptLinker: null,
        receiptLinkTel: null,
        actualCarrierName: null,
        actualCarrierBusinessLicense: null,
        actualCarrierId: null,
        vehicleNumber: null,
        vehiclePlateColorCode: null,
        policyNumber: null,
        insuranceCompanyCode: null,
        startLongitude: null,
        startLatitude: null,
        endLongitude: null,
        endLatitude: null,
        isSendToPro: '1',
        sendToProDateTime: null,
        companyId: null,
        companyName: null,
        type: '2',
        source: null,
        pointId: null,
        pointLabel: null,
        leaveTime: null,
        arriveTime: null,
        vehicleId: null,
        driverId: null,
        driverName: null,
        driverPhone: null,
        isBill: null,
        isReceipt: null,
        status: "1",
        tenantId: null,
        startTime: null,
        endTime: null,
        remark: null,
        backImages: null,
        lossAmount: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        fValue: [],
        sValue: []
      };
      this.resetForm("form");
      this.is_bx = true;
      this.form.policyNumber = '';
      this.form.insuranceCompanyCode = '';
      this.opCompany = [];
      this.opDriver = [];
      this.sumFlowIn = 0.00;
      this.sumFlowOut = 0.00;
      this.flowTotal = 0.00;
      this.flowListIn = [];
      this.flowListOut = [];
      this.readOnly1 = false;
      this.readOnly2 = false;
      this.fileList = [];
    },
    // 选择了货源方
    changeCompany(val) {
      this.form.consignorId = val.taxpayercard;
      this.form.consignor = val.shortName;
      this.form.companyId = val.id;
      this.form.loadLinker = val.linker;
      this.form.loadLinkTel = val.linktel;
      this.opCompany = [];
      this.opCompany.push(val);
      // 将应收列表的客户全选为当前货源方
      this.flowListIn.forEach(el => {
        el.companyId = val.id;
      })
    },
    // 选择了司机
    changeDriver(val) {
      this.form.driverId = val.id;
      // 查询车辆
      let queryParam = {
        driverId: val.id,
        isCert: '2',
        state: '1'
      }
      listVehicleAll(queryParam).then(response => {
        this.vehicleOptions = response.data;
      });
      this.form.actualCarrierName = val.driverName;
      this.form.actualCarrierId = val.drivingLicense;
      this.form.driverPhone = val.telephone;
      this.opDriver = [];
      this.opDriver.push(val);
      // 将应付列表的司机全选为当前司机
      this.flowListOut.forEach(el => {
        el.driverId = val.id;
      })
    },
    // 选择了车辆
    changeVehicle(val) {
      this.form.vehicleNumber = val.vehicleNumber;
      this.form.vehicleId = val.id;
      this.form.vehiclePlateColorCode = val.vehiclePlateColorCode;
      this.form.actualCarrierBusinessLicense = val.roadTransportCertificateNumber;
      if(this.form.goodsItemGrossWeight) {
        let hz = val.vehicleTonnage * 1000;
        if(this.form.goodsItemGrossWeight > hz) {
          this.$alert('该车辆核载为 ' + hz + ' KG，有超载风险！(如果是牵引车请忽略本警告)', '警告', {
            confirmButtonText: '确定'
          }).catch(() => {
          })
        }
      }
    },
    // 选择了挂车
    changeVehicleG(val) {
      this.form.trailerVehiclePlateNumber = val.vehicleNumber;
      this.form.trailerVehicleId = val.id;
      this.form.trailerVehiclePlateColorCode = val.vehiclePlateColorCode;
      if(this.form.goodsItemGrossWeight) {
        let hz = val.vehicleTonnage * 1000;
        if(this.form.goodsItemGrossWeight > hz) {
          this.$alert('挂车核载为 ' + hz + ' KG，有超载风险！', '警告', {
            confirmButtonText: '确定'
          }).catch(() => {
          })
        }
      }
    },
    // 清除了挂车
    clearVehicleG() {
      this.form.trailerVehiclePlateNumber = '';
      this.form.trailerVehicleId = null;
      this.form.trailerVehiclePlateColorCode = '';
    },
    // 装货地省市区联动
    handleChangeF(value) {
      // 取最后一级的代码
      this.form.countrySubdivisionCode = value[value.length - 1]
      this.form.countrySubdivisionValue = value.join("-")
      let name = '';
      value.forEach(element => {
        name = name + CodeToText[element];
      });
      this.form.countrySubdivisionLabel = name;

      // 如果装货地址不为空,获取发货地址的经纬度
      if(this.form.placeOfLoading) {
        this.getFLocation()
      }
    },
    // 收货地省市区联动
    handleChangeS(value) {
      // 取最后一级的代码
      this.form.countrySubdivisionCodeS = value[value.length - 1]
      this.form.countrySubdivisionValueS = value.join("-")
      let name = '';
      value.forEach(element => {
        name = name + CodeToText[element];
      });
      this.form.countrySubdivisionLabelS = name;

      // 如果收货地址不为空,获取收货地址的经纬度
      if(this.form.goodsReceiptPlace) {
        this.getSLocation();
      }
    },
    blurF() {
      if(this.form.countrySubdivisionLabel) {
        this.getFLocation();
      }
    },
    blurS() {
      if(this.form.countrySubdivisionLabelS) {
        this.getSLocation();
      }
    },
    // 获取发货地址的经纬度
    getFLocation() {
      let address = this.form.countrySubdivisionLabel + this.form.placeOfLoading;
      this.geocoder.getLocation(address, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          this.form.startLongitude = result.geocodes[0].location.lng;
          this.form.startLatitude = result.geocodes[0].location.lat;
        }
      });
    },
    // 获取收货地址的经纬度
    getSLocation() {
      let address = this.form.countrySubdivisionLabelS + this.form.goodsReceiptPlace;
      this.geocoder.getLocation(address, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          this.form.endLongitude = result.geocodes[0].location.lng;
          this.form.endLatitude = result.geocodes[0].location.lat;
        }
      });
    },
    // 隐藏保险信息
    ycBx() {
      this.is_bx = false;
      this.form.policyNumber = 'none';
      this.form.insuranceCompanyCode = 'none';
    },
    // 添加保险信息
    tjBx() {
      this.is_bx = true;
      this.form.policyNumber = '';
      this.form.insuranceCompanyCode = '';
    },
    /** 添加行数据 */
    addLine(i) {
      // 应收
      if(i == 1){
        this.flowListIn.push({
          flowType: null,
          amount: 0,
          companyId: this.form.companyId || null,
          driverId: null
        });
      //应付
      } else {
        this.flowListOut.push({
          flowType: null,
          amount: 0,
          companyId: null,
          driverId: this.form.driverId || null
        });
      }
    },
    /** 删除行数据 */
    delLine:function(index, row, i){//删除行数
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除该数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        if(row.id){     //已存在DB中
          return delFlow(ids);
        }
      }).then(() => {
        //删除元素
        if(i == 1) {//应收
          this.flowListIn.splice(index, 1)
        }else{//应付
          this.flowListOut.splice(index, 1)
        }
        //重新计算统计
        this.sumFlow();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {})
    },
    /** 底部统计 */
    sumFlow: function() {
      this.$nextTick(() => {//时机似乎有点问题 -- 处理下
        this.sumFlowIn = 0.00;
        this.sumFlowOut = 0.00;
        //应收
        for (let i = 0; i < this.flowListIn.length; i++) {
          if(!isNaN(this.flowListIn[i].amount)){
            this.sumFlowIn += Number(this.flowListIn[i].amount);
          }
        }
        //应付
        for (let i = 0; i < this.flowListOut.length; i++) {
          if(!isNaN(this.flowListOut[i].amount)){
            this.sumFlowOut += Number(this.flowListOut[i].amount);
          }
        }
        this.sumFlowIn = this.sumFlowIn.toFixed(2);
        this.sumFlowOut =  this.sumFlowOut.toFixed(2);

        //利润
        this.flowTotal = (this.sumFlowIn - this.sumFlowOut).toFixed(2);
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.disabled = true;
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 运费金额
          if(this.form.totalMonetaryAmount <= 1) {
            this.$modal.msgError("请调整运费金额");
            this.disabled = false;
            throw Error("请调整运费金额");//中断后续操作
          }
          //流水 不能同时选择客户或司机
          this.flowListIn.forEach( evn => {
            if(evn.amount && !evn.flowType) {
              this.$modal.msgError("请选择费用类型");
              this.disabled = false;
              throw Error("请选择应收的费用类型");//中断后续操作
            }
            if(evn.amount && evn.companyId && evn.driverId){
              this.$modal.msgError("货源方与司机不能同时选择");
              this.disabled = false;
              throw Error("货源方与司机不能同时选择");//中断后续操作
            }
            if(evn.amount && !evn.companyId && !evn.driverId){
              this.$modal.msgError("货源方与司机二选一");
              this.disabled = false;
              throw Error("货源方与司机二选一");//中断后续操作
            }
          })
          this.flowListOut.forEach( evn => {
            if(evn.amount && !evn.flowType) {
              this.$modal.msgError("请选择费用类型");
              this.disabled = false;
              throw Error("请选择应付的费用类型");//中断后续操作
            }
            if(evn.amount && evn.companyId && evn.driverId){
              this.$modal.msgError("货源方与司机不能同时选择");
              this.disabled = false;
              throw Error("货源方与司机不能同时选择");//中断后续操作
            }
            if(evn.amount && !evn.companyId && !evn.driverId){
              this.$modal.msgError("货源方与司机二选一");
              this.disabled = false;
              throw Error("货源方与司机二选一");//中断后续操作
            }
          })
          let d = {};
          d.order = this.form;
          d.flowListIn = this.flowListIn;
          d.flowListOut = this.flowListOut;
          if (this.form.id != null) {
            if(this.form.type == '1') {
              d.order.type = '2';
              d.order.source = '1';
              d.order.status = '1';
            }
            updateOrder(d).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.disabled = false;
              this.huidiao();
            }).catch(err => {
              this.disabled = false;
            })
          } else {
            d.order.type = '2';
            d.order.source = '2';
            addOrder(d).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.disabled = false;
              this.huidiao();
            }).catch(err => {
              this.disabled = false;
            })
          }
        } else {
          this.disabled = false;
        }
      });
    }
  }
};
</script>

<style>
  .select {
    width: 100%;
  }
  .divider_color {
    color: #409eff;
  }
  .o_input {
    width: 130%;
  }
  .o_select {
    width: 121%;
  }
  .o_picker {
    width: 113%;
  }
  .specBtn {
    position: absolute;
    left: 10px;
    top: 5px;
    z-index: 99;
  }
  .specBtn2 {
    position: absolute;
    right: 47%;
    top: 5px;
    z-index: 99;
  }
</style>
